class GalleryController < ApplicationController
  PER_PAGE = 30
  def index
    @image_pages, @images = paginate(:images,:order_by=>'sequence',:conditions=>"publish=true", :per_page => PER_PAGE)
    @categories = Category.find(:all,:order=>'sequence')
    @cur_category= ""
  end
  def view_image
    @full=Image.find(params[:id])
    render :partial=>'full',:layout=>false
  end
  def view_thumb
    @image_pages, @images = paginate(:images,:order_by=>'sequence',:conditions=>"category_id=#{params[:id]} AND publish=true", :per_page => PER_PAGE)
    @cur_category_children=Category.find(params[:id]).children.find(:all)
    @cur_category_name=Category.find(params[:id]).name
    
    render :partial=>'thumbnail',:layout=>false    
  end
  def search    
    keyword=params[:search][:keyword]
    if !keyword.empty?
      
      keyword=keyword.gsub(/\s/,"+.*")
      query=""
      if params[:search][:brief_descr] == "1"
          query+="or" if query !=""
          query+="(brief_descr rlike '.*#{keyword}+.*') "         
      end
      if params[:search][:full_descr] == "1"
        query+="or" if query !=""
        query+="(full_descr rlike '.*#{keyword}+.*') "          
      end
      if params[:search][:name] == "1"
        query+="or" if query !=""
        query+="(name rlike '.*#{keyword}+.*')"       
      end
      if params[:search][:author] == "1"
        query+="or" if query !=""
        query+="(author rlike '.*#{keyword}+.*')"       
      end    

      @image_pages, @images = paginate(:images,:order_by=>'sequence',:conditions=>query, :per_page => PER_PAGE)

      keyword=params[:search][:keyword]
      keyword=keyword.split
      keyword.each{|key| 
        patern=Regexp.new(key,Regexp::IGNORECASE)
        @images.each{|image|
          image.brief_descr.sub!(patern){|str|
              str.insert(0,"<font class='hightlight'>")
              str.insert(-1,"</font>")
              }
          image.full_descr.sub!(patern){|str|
              str.insert(0,"<font class='hightlight'>")
              str.insert(-1,"</font>")            
              }
          image.name.sub!(patern){|str|
              str.insert(0,"<font class='hightlight'>")
              str.insert(-1,"</font>")
              }
          image.author.sub!(patern){|str|
              str.insert(0,"<font class='hightlight'>")
              str.insert(-1,"</font>")
                }
        }
      }
    else
      @image_pages, @images = paginate(:images,:order_by=>'sequence', :per_page => PER_PAGE)
    end
    @categories = Category.find(:all,:order=>'sequence')
    @cur_category= ""
    
    render :partial=>'thumbnail',:layout=>false    
  end
end